var express = require("express")
var router = express.Router()
const shortid = require("shortid") //shortid是一个用于生成短唯一ID的轻量级npm包
// lowdb配置
const low = require("lowdb") // 并提供了简单易用的API来读取、写入和查询JSON数据
const FileSync = require("lowdb/adapters/FileSync")
const adapter = new FileSync(__dirname + "/../data/db.json") // 储存文件 写入数据
const db = low(adapter) // 获取 db 对象

// 默认
router.get("/", function (req, res, next) {
  res.render("index", { title: "express" })
})
// 记账本
router.get("/account", function (req, res, next) {
  let accounts = db.get("accounts").value() // 获取账单信息 data/db/json
  res.render("list", { accounts })
})
// 添加记录
router.get("/account/create", function (req, res, next) {
  res.render("create")
})
// 点击删除
router.get("/account/:id", (req, res) => {
  let id = req.params.id
  db.get("accounts").remove({ id }).write()
  res.render("success", { msg: "删除成功~~~", url: "/account" }) // 提醒
})
// 添加记录点击添加POST请求
router.post("/account", function (req, res, next) {
  let id = shortid.generate() // 生成ID
  // 写入文件
  db.get("accounts")
    .unshift({ id, ...req.body })
    .write()
  res.render("success", { msg: "添加成功", url: "/account" })
})

module.exports = router
